package com.example.communication;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhangs
 * @version v1.0
 * @decription Condition接口中的await和signal方法
 * @date 2021/3/28 12:57
 **/
public class AwaitAndSignal {
    final static Lock LOCK = new ReentrantLock();
    final static Condition CONDITION = LOCK.newCondition();

    public static void main(String[] args) {
        new Thread(() -> {
            // 加锁
            LOCK.lock();
            Thread curr = Thread.currentThread();
            try {
                System.out.println(curr.getName() + " start!");
                // 暂停当前线程，并释放锁
                CONDITION.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // 解锁
                LOCK.unlock();
            }
            System.out.println(curr.getName() + " end!");
        }, "t1").start();

        new Thread(() -> {
            // 加锁
            LOCK.lock();
            Thread curr = Thread.currentThread();
            try {
                System.out.println(curr.getName() + " start!");
                // 唤醒同步在LOCK的线程，但不释放锁的占用
                CONDITION.signal();
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // 解锁
                LOCK.unlock();
            }
            System.out.println(curr.getName() + " end!");
            System.out.println("Condition.signal不释放锁！");
        }, "t2").start();
    }
}
